package com.linmo.historymanage;

import com.linmo.chatmanage.ChatJPanelGUI;
import com.linmo.chatmanage.ChatManage;
import com.linmo.chatmanage.SessionRecordDTO;
import com.linmo.util.ChatBotThread;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.concurrent.ExecutorService;

public class HistoryGuI extends JPanel {
    private static final HistoryManage historyManage = new HistoryManage();
    private static final ChatManage chatManage = new ChatManage();

    private ChatJPanelGUI chatJPanelGUI;
    private JTable historyTable;
    private DefaultTableModel tableModel;
    private JButton clearHistoryButton;

    public HistoryGuI(int userId, ChatJPanelGUI chatJPanelGUI) {
        this.chatJPanelGUI = chatJPanelGUI;
        setLayout(new BorderLayout());

        // 初始化表格模型
        tableModel = new DefaultTableModel(new String[]{"会话序号", "开始时间", "结束时间"}, 0);
        historyTable = new JTable(tableModel);
        historyTable.setDefaultEditor(Object.class, null); // 禁用所有单元格的编辑

        // 添加滚动条
        JScrollPane scrollPane = new JScrollPane(historyTable);
        add(scrollPane, BorderLayout.CENTER);

        // 加载历史记录
        reloadHistoryRecords(userId);

        // 添加点击事件
        historyTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                if (evt.getClickCount() == 2) { // 双击事件
                    int selectedRow = historyTable.getSelectedRow();
                    if (selectedRow != -1) { // 确保选中了一行
                        int sessionId = (int) tableModel.getValueAt(selectedRow, 0);
                        System.out.println("Selected Session ID: " + sessionId); // 调试信息

                        ChatBotThread.execute(new Runnable() {
                            @Override
                            public void run() {
                                List<SessionRecordDTO> sessionRecords = chatManage.loadSessionMessages(sessionId);
                                System.out.println("Loaded Session Records: " + sessionRecords.size()); // 调试信息

                                SwingUtilities.invokeLater(new Runnable() {

                                    @Override
                                    public void run() {
                                        // 清空会话区
                                        chatJPanelGUI.clearChatArea();
                                        // 设置当前会话ID
                                        chatJPanelGUI.setCurrentSessionId(sessionId);
                                        // 遍历会话记录并显示在会话区
                                        for (SessionRecordDTO record : sessionRecords) {
                                            if (record.getRole().equals("User")) {
                                                System.out.println("Appending User Message: " + record.getMessage()); // 调试信息
                                                chatJPanelGUI.getAppend("User: " + record.getMessage() + "\n");
                                            } else if (record.getRole().equals("Linmo")) {
                                                System.out.println("Appending Linmo Message: " + record.getMessage()); // 调试信息
                                                chatJPanelGUI.getAppend("Linmo: " + record.getMessage() + "\n");
                                            }
                                        }
                                    }
                                });
                            }
                        });

//                        List<SessionRecordDTO> sessionRecords = chatManage.loadSessionMessages(sessionId);
//                        System.out.println("Loaded Session Records: " + sessionRecords.size()); // 调试信息

//                        // 清空会话区
//                        chatJPanelGUI.clearChatArea();
//                        // 设置当前会话ID
//                        chatJPanelGUI.setCurrentSessionId(sessionId);
//                        // 遍历会话记录并显示在会话区
//                        for (SessionRecordDTO record : sessionRecords) {
//                            if (record.getRole().equals("User")) {
//                                System.out.println("Appending User Message: " + record.getMessage()); // 调试信息
//                                chatJPanelGUI.getAppend("User: " + record.getMessage() + "\n");
//                            } else if (record.getRole().equals("Linmo")) {
//                                System.out.println("Appending Linmo Message: " + record.getMessage()); // 调试信息
//                                chatJPanelGUI.getAppend("Linmo: " + record.getMessage() + "\n");
//                            }
//                        }
                    } else {
                        System.out.println("No row selected!"); // 调试信息
                    }
                }
            }
        });

        // 添加清空历史按钮
        clearHistoryButton = new JButton("清空历史");
        clearHistoryButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                clearHistory(userId);
            }
        });

        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 0));
        buttonPanel.add(clearHistoryButton);

        // 添加按钮面板到界面
        add(buttonPanel, BorderLayout.SOUTH);
    }

    // 重新加载历史记录
    public void reloadHistoryRecords(int userId) {
        tableModel.setRowCount(0); // 清空表格
        List<HistoryRecordDTO> loadedHistory = historyManage.loadHistory(userId);
        if (loadedHistory != null) {
            for (HistoryRecordDTO record : loadedHistory) {
                // 将记录添加到表格模型中
                tableModel.addRow(new Object[]{record.getSessionId(), record.getCreateTime(), record.getUpdateTime()});
            }
        }
    }

    // 清空历史记录
    private void clearHistory(int userId) {
        int result = JOptionPane.showConfirmDialog(this, "确定要清空历史记录吗？", "清空历史记录", JOptionPane.YES_NO_OPTION);
        if (result == JOptionPane.YES_OPTION) {
            // 调用历史管理模块的清空历史记录方法
            historyManage.clearHistory(userId);
            // 重新加载历史记录
            reloadHistoryRecords(userId);
            JOptionPane.showMessageDialog(this, "历史记录已清空");
        }
    }

    public void shutdown() {
        ChatBotThread.shutdown();
    }
}
